#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>

#include "struc_arg.h"
#include "process.h"

#define MAX_SIZE 1024

/**FUNCTION*******************************************/
char* getPaths(int pPathNumber, char** p)
{
    return p[pPathNumber];
}

/**FUNCTION*******************************************/
int startProcessing( const arg_t* pArgs )
{
    int result = 0;
    int currentPath = 2;
    while( pArgs->pathSize_ > currentPath )
    {
        char* path = getPaths(currentPath, pArgs->paths_);
        ++currentPath;
        if( argIsFile(path) )
        {
            basicLookout(path, pArgs->paths_[1]);
           //Parses single file
        }
        else if( argIsFolder(path) )
        {
            basicLookoutFolder(path, pArgs->paths_[1]);
        }
        else
        {
            printf("Can't open %s\n", path);
        }
    }

    return result;
}

/**FUNCTION*******************************************/
int argIsFile(const char* pPath)
{
    FILE * file = fopen(pPath, "r+");

    if (file != NULL)
    {
        basicLookout(pPath, "int");
        return 1;
    }
    return 0;
}

/**FUNCTION*******************************************/
int argIsFolder(const char* pPath)
{
    DIR * dir = opendir(pPath);

    if (dir != NULL)
    {
        return 1;
    }
    return 0;
}

/**FUNCTION*******************************************/
void basicLookout(const char* pPath, const char* pStr)
{
    FILE * file = fopen(pPath, "r+");
    char line[MAX_SIZE];
    int lineNumber = 0;
    if (file != NULL)
    {
        while( NULL != fgets(line, MAX_SIZE, file) )
        {
            ++lineNumber;
            if( NULL != strstr(line, pStr) )
            {
                printf("%s:%i\t%s", pPath, lineNumber, line);
            }

        }
    }
}

/**FUNCTION*******************************************/
void basicLookoutFolder(const char* pPath, const char* pStr)
{
     DIR * dir = opendir(pPath);

    if (dir != NULL)
    {
        printf("Folder : %s\n", pPath);
        struct dirent * ent;

        while ((ent = readdir(dir)) != NULL)
        {
            basicLookout(ent->d_name, pStr);
        }

        closedir(dir);
    }
}

/**FUNCTION*******************************************/
void printMessage(const char* pMessage, int pType)
{

}
